package com.study.securitydemo.config;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author weiyongpeng
 * @ClassName: MyAuthenticationSuccessHandler
 * @Description: 认证成功的处理器
 * @date 2024/10/26
 */
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        // 用户身份信息
        Object principal = authentication.getPrincipal();
        // 用户凭证信息(密码)
        Object principal1 = authentication.getPrincipal();

        Map result = new HashMap();
        result.put("code",0);
        result.put("message","登陆成功");
        result.put("data", principal);

        // 创建json结果,将结果转化为json字串
        String json = JSON.toJSONString(result);
        // 将json字串返回前端
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
    }
}